/*
 * 版权：Copyright (c) 2019 红网
 * 
 * 创建日期：Wednesday January 30th 2019
 * 创建者：胡燕龙(huyl) - y.dragon.hu@hotmail.com
 * 
 * 修改日期: Wednesday, 30th January 2019 10:33:03 am
 * 修改者: 胡燕龙(huyl) - y.dragon.hu@hotmail.com
 * 
 * 说明
 * 		1、
 */
import { Dropdown, Icon, Layout, Menu, Row } from "antd";
import { NavBar, TabBar, Toast } from "antd-mobile";
import { addon, PermissionState } from "pao-aop";
import { CommonIcon, LinkObject, MenuItem, reactControl, ReactMainForm, ReactMainFormControl, ReactMainFormState } from "pao-aop-client";
import React from "react";
import { LOCAL_FUNCTION_LIST } from "src/business/mainForm/backstageManageMainForm";
import { getWebViewRetObjectType, subscribeWebViewNotify } from "src/business/util_tool";
import { getAppPermissonObject } from "src/projects/app/util-tool";
import './index.less';
import { IntelligentElderlyCareAppStorage } from "src/projects/app/appStorage";
// import { ROUTE_PATH } from "src/projects/app/util-tool";
let { Content } = Layout;
/** 状态：手机应用窗体 */
export interface AppMainFormState extends ReactMainFormState {
    title?: string;
    open?: boolean;
}
/** 组件：手机应用窗体 */
export class AppMainForm extends ReactMainForm<AppMainFormControl, AppMainFormState> {
    /** 手机应用窗体 */
    constructor(props: AppMainFormControl) {
        super(props);
        this.state = {
            open: false,
            title: undefined
        };
    }

    /** 创建下拉菜单工具 */
    createDropdown(linkObject: LinkObject) {
        const { key, title, icon, link, onClick, childLinkObjects } = linkObject;
        const menu = (
            <Menu>
                {
                    childLinkObjects!.map(item => {
                        return <MenuItem key={key!} title={title} icon={icon} link={link} onClick={onClick} />;
                    })
                }
            </Menu>);
        return (
            <Dropdown overlay={menu}>
                <MenuItem key={key!} title={title} icon={icon} link={link} onClick={onClick} />
            </Dropdown>
        );
    }
    componentDidMount() {
        const messageCb = (e: any) => {
            const retObject = JSON.parse(e.data);
            if (getWebViewRetObjectType(retObject) === 'ScanQRCode') {
                // Toast.info(e.data);
                const scanURL = new URL(retObject.data);

                if (scanURL.hostname === window.location.hostname) {
                    this.props.history!.push(scanURL.pathname);
                } else {
                    Toast.fail('请扫描本平台生成的二维码');
                }
            }
        };

        subscribeWebViewNotify(messageCb);
    }

    ScanQRCode() {
        if ((window as any).ReactNativeWebView) {
            (window as any).ReactNativeWebView.postMessage(
                JSON.stringify({
                    function: 'ScanQRCode',
                    params: undefined
                })
            );
        } else {
            Toast.fail('启用相机功能失败');
        }
    }

    /** 获取标题根据路由 */
    getTitleByRoute() {
        const { location, mainMenus } = this.props;
        const { pathname } = location!;
        let linkObject = mainMenus!.find(item => {
            if (item.link === pathname) {
                return true;
            }
            return false;
        });
        if (linkObject) {
            return linkObject.title;
        }
        return this.props.title;
    }
    /** 返回按钮回调 */
    icon_click = () => {
        let back_url = this.props.icon_click;
        this.props.history!.push(back_url!);
    }
    onOpenChange = () => {
        this.setState({ open: !this.state.open });
    }
    menuIcon = () => {
        this.setState({
            open: true,
        });
    }
    menuClick = (url: string) => {
        this.setState({
            open: false,
        });
        this.props.history!.push(url);
    }

    getTab = () => {
        let tabBarMenu: JSX.Element[] = [];
        const { mainMenus, location, history, view } = this.props;
        const { pathname } = location!;
        mainMenus!.map(menu => {
            // 判断是否登录
            const func_list_str = localStorage.getItem(LOCAL_FUNCTION_LIST);
            const userInfo = (IntelligentElderlyCareAppStorage.getCurrentUser() as any);
            if (func_list_str && userInfo) {
                // 已登录
                if (['我的', '老友圈', '服务热线', '搜索', '互动', '资讯发布', '消息提醒'].indexOf(menu.title!) !== -1) {
                    if (getAppPermissonObject(JSON.parse(func_list_str!), menu.title!, '查询')) {
                        /** 
                         * getAppPermissonObject(this.AppPermission, '搜索', '查询')
                         * 查询'搜索'的查询权限，拥有返回true，没有就返回false
                         */

                        menu['permission'] = { permission_state: PermissionState.grant };
                    } else {
                        menu['permission'] = { permission_state: PermissionState.forbid };
                    }
                } else {
                    if (menu.title !== '首页') {
                        menu['permission'] = { permission_state: PermissionState.forbid };
                    }
                }
            } else {
                // 未登录
                if (['首页', '我的', '老友圈', '服务热线', '搜索', /*'互动', '资讯发布', '消息提醒' */].indexOf(menu.title!) !== -1) {
                    menu['permission'] = { permission_state: PermissionState.grant };
                } else {
                    menu['permission'] = { permission_state: PermissionState.forbid };
                }
            }
            if (menu.permission && menu.permission!.permission_state === PermissionState.grant) {
                tabBarMenu.push(
                    tabBarMenu.length === 2 ?
                        (
                            <TabBar.Item
                                icon={<div className='icon-circle'><CommonIcon icon={menu.icon} /></div>}
                                selectedIcon={<div className={'icon-circle'}><CommonIcon icon={menu.icon} /></div>}
                                key={menu.title!}
                                selected={menu.link === pathname}
                                onPress={() => {
                                    history!.push(menu.link!);
                                }}
                            >
                                <Content className='layout-conten-no-icon pd45'>
                                    {
                                        view
                                    }
                                </Content>
                            </TabBar.Item>
                        )
                        :
                        (
                            <TabBar.Item
                                icon={<CommonIcon icon={menu.icon} />}
                                selectedIcon={<CommonIcon icon={menu.icon} />}
                                title={menu.title!}
                                key={menu.title!}
                                selected={menu.link === pathname}
                                onPress={() => {
                                    history!.push(menu.link!);
                                }}
                            >
                                <Content className='layout-conten-no-icon pd45'>
                                    {
                                        view
                                    }
                                </Content>
                            </TabBar.Item>
                        )
                );
            }
        });

        const tabBar = (
            <TabBar>
                {
                    tabBarMenu
                }
            </TabBar>
        );
        return tabBar;
    }

    render() {
        const { isHiddenTool, is_home } = this.props;
        // const sidebar = (
        //     <List>
        //         {
        //             this.props.menuList ? this.props.menuList!.map((item: any, index) => {
        //                 return (
        //                     <List.Item
        //                         key={index}
        //                         thumb={<Icon type={item.icon} />}
        //                         multipleLine={true}
        //                         onClick={this.menuClick.bind(this, item.url)}
        //                     >
        //                         {item.text}
        //                     </List.Item>
        //                 );
        //             }) : ''
        //         }
        //     </List>
        // );
        // const myImg = (src: any) => <img src={`https://gw.alipayobjects.com/zos/rmsportal/${src}.svg`} className="am-icon am-icon-xs" alt="" />;
        const navBar = (
            <NavBar
                id={'appMainFormNavBar'}
                // icon={is_home ? <Icon type="menu-unfold" style={{ fontSize: '24px' }} onClick={this.menuIcon} /> : <Icon type={"left"} onClick={this.icon_click} />}
                icon={is_home ? '' : <Icon type={"left"} onClick={this.icon_click} />}
                rightContent={<Icon type="scan" onClick={this.ScanQRCode} />}
            >
                {
                    this.getTitleByRoute()
                }
            </NavBar>
        );

        return (
            <Layout className='main-form-content'>
                {
                    // is_home ?
                    //     <Drawer
                    //         className="my-drawer"
                    //         style={{ minHeight: document!.documentElement!.clientHeight }}
                    //         enableDragHandle={false}
                    //         contentStyle={{ color: '#A6A6A6', overflowY: 'auto', textAlign: 'center', display: 'flex', flexDirection: 'column' }}
                    //         sidebar={sidebar}
                    //         open={this.state.open}
                    //         onOpenChange={this.onOpenChange}
                    //     >
                    //         {
                    //             !isHiddenTool ? navBar : null
                    //         }
                    //         {tabBar}
                    //     </Drawer>
                    //     :
                }
                <Row style={{ overflowY: 'auto', height: '100%' }}>
                    {
                        !isHiddenTool ? navBar : null
                    }
                    {this.getTab()}
                </Row>
            </Layout>);
    }
}

/**
 * 控件：手机应用窗体控制器
 * @description 用于手机应用的主窗体
 */
@addon('AppMainForm', '手机应用窗体', '用于手机应用的主窗体')
@reactControl(AppMainForm, true)
export class AppMainFormControl extends ReactMainFormControl {
    /**
     * 手机应用窗体控制器
     * @param title 应用标题
     * @param mainMenus 主菜单
     * @param toolButtons 工具条
     */
    constructor(
        public title?: string,
        public mainMenus?: LinkObject[],
        public toolButtons?: LinkObject[],
        public isHiddenTool?: boolean,
        public icon_click?: string,
        public is_home?: boolean,
        public menuList?: any[]) {
        super();
    }
}
